package com.yl.login.ui

import android.text.TextUtils
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.yl.common.base.BaseActivity
import com.yl.common.exp.Constants
import com.yl.common.network.BaseResp
import com.yl.common.network.BaseStateObserver
import com.yl.common.util.KVUtil
import com.yl.common.util.ToastUtil
import com.yl.login.R
import com.yl.login.bean.LoginBean
import com.yl.login.databinding.ActivityLoginBinding
import com.yl.login.viewmodel.LoginViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel

@Route(path = Constants.LOGIN_ACTIVITY, name = "登录页")
class LoginActivity : BaseActivity<ActivityLoginBinding>() {

    private val loginViewModel: LoginViewModel by viewModel()


    override fun getLayoutID() = R.layout.activity_login

    override fun init() {
        mBind.login.setOnClickListener {
//            startActivity<HomeActivity>()
//            ARouter.getInstance().build(Constants.MAIN_ACTIVITY ).navigation()
//            finish()
            showLoadingDialog()
            verify()
        }

        mBind.imgBack.setOnClickListener {
            finish()
        }

        loginViewModel.loginData.observe(this, object : BaseStateObserver<LoginBean>(null) {
            override fun getRespDataSuccess(it: BaseResp<LoginBean>) {
                Log.e(TAG, it.data.toString())
                KVUtil.put(Constants.USER_NAME, it.data!!.username)
                KVUtil.put(Constants.USER_PASSWORD, mBind.password.text.toString())
                ToastUtil.showMsg("登陆成功！")
                dismissLoadingDialog()
                ARouter.getInstance().build(Constants.MAIN_ACTIVITY).navigation()
                finish()
            }
        })
    }

    private fun verify() {
        val usernameText = mBind.username.text.toString()
        val passwordText = mBind.password.text.toString()

        if (TextUtils.isEmpty(usernameText)) {
            ToastUtil.showMsg("用户名不能为空")
            return
        }
        if (TextUtils.isEmpty(passwordText)) {
            ToastUtil.showMsg("密码不能为空")
            return
        }
        upData(usernameText, passwordText)
    }

    override fun initData() {}

    override fun onResume() {
        super.onResume()
        mBind.username.setText(KVUtil.getString(Constants.USER_NAME))
        mBind.password.setText(KVUtil.getString(Constants.USER_PASSWORD))
    }

    private fun upData(usernameText: String, passwordText: String) {
        loginViewModel.login(usernameText, passwordText)
    }


}